package enterprisePerson

import (
	"context"
	"errors"
	"github.com/google/uuid"
	"github.com/kuangshp/go-utils/k"
	"gorm.io/gorm"
	"insighttracking/apps/admin/auth"
	"insighttracking/common/enum"
	"insighttracking/query/dao"
	"net/http"

	"insighttracking/apps/admin/internal/svc"
	"insighttracking/apps/admin/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
	"os"
)

type ModifyEnterprisePersonStatusByIdApiLogic struct {
	logx.Logger
	ctx     context.Context
	svcCtx  *svc.ServiceContext
	Request *http.Request
}

func NewModifyEnterprisePersonStatusByIdApiLogic(ctx context.Context, svcCtx *svc.ServiceContext, request *http.Request) *ModifyEnterprisePersonStatusByIdApiLogic {
	hostname, _ := os.Hostname()
	return &ModifyEnterprisePersonStatusByIdApiLogic{
		Logger: logx.WithContext(ctx).WithCallerSkip(0).WithFields(
			logx.Field("Log_UUID", uuid.New().String()),
			logx.Field("hostname", hostname)),
		ctx:     ctx,
		svcCtx:  svcCtx,
		Request: request,
	}
}

func (l *ModifyEnterprisePersonStatusByIdApiLogic) ModifyEnterprisePersonStatusByIdApi(req *types.IdReq) (resp string, err error) {
	// todo: add your logic here and delete this line
	accountInfo, err := auth.GetAccountInfo(l.svcCtx, l.Request)
	if err != nil {
		return "", err
	}
	if accountInfo.AccountType != enum.EnterpriseEnum {
		return "", errors.New("只有企业账号才能操作")
	}
	enterprisePerson, err := dao.EnterprisePersonEntity.WithContext(l.ctx).Where(
		dao.EnterprisePersonEntity.EnterpriseID.Eq(accountInfo.EnterpriseId),
		dao.EnterprisePersonEntity.ID.Eq(req.Id),
	).First()
	if errors.Is(err, gorm.ErrRecordNotFound) {
		return "", errors.New("传递的主键错误")
	}
	tx := dao.Use(l.svcCtx.MysqlDb).Begin()
	status := k.If(enterprisePerson.Status == 0, 1, 0)
	if _, err = tx.EnterprisePersonEntity.WithContext(l.ctx).Where(dao.EnterprisePersonEntity.ID.Eq(req.Id)).UpdateSimple(
		dao.EnterprisePersonEntity.Status.Value(int64(status)),
	); err != nil {
		if err = tx.Rollback(); err != nil {
			return "", err
		}
		return "", errors.New("修改失败")
	}
	// 修改账号的
	if _, err = tx.AccountEntity.WithContext(l.ctx).Where(
		dao.AccountEntity.EnterpriseID.Eq(accountInfo.EnterpriseId),
		dao.AccountEntity.PersonID.Eq(req.Id),
	).UpdateSimple(dao.AccountEntity.Status.Value(int64(status + 1))); err != nil {
		if err = tx.Rollback(); err != nil {
			return "", err
		}
		return "", errors.New("修改失败")
	}
	if err = tx.Commit(); err != nil {
		return "", errors.New("修改失败")
	}
	return "修改成功", nil
}
